package dataAccess;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;

import javax.swing.JOptionPane;

public class DataAccess {
	private ArrayList<String> listWord = new ArrayList<String>();

	/**
	 * Doc mot file len voi duong dan path cua file do
	 * 
	 * @param path
	 * @return
	 */
	public String readFile(String path) {
		String text = "";
		try {
			String line;
			BufferedReader bf = new BufferedReader(new FileReader(
					new File(path)));

			while ((line = bf.readLine()) != null) {
				text += line +"\n";
			}
			if(text.endsWith("\n"))
				text.substring(0, text.length() - 1);
			bf.close();
		} catch (Exception e) {
		}

		return text;
	}
	
	/**
	 * read file help tu directory
	 * @param file
	 * @return
	 */
	public String readFileUTF8(String path) {
		File file = new File(path);
		String text = "";
		Charset cs = Charset.forName("UTF-8");
		try (BufferedReader reader = Files.newBufferedReader(file.toPath(), cs)) {
			String line;

			while ((line = reader.readLine()) != null) {
				text += line + "\n";
			}
			reader.close();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null,
					"File not found. Please try another path", "Message", 0,
					null);
		}
		return text;
	}

	/**
	 * Doc file database.txt len va cho word vao trong list
	 */
	private void readFileDatabase() {
		try {
			String line;
			BufferedReader bf = new BufferedReader(new FileReader(new File(
					"src/dataAccess/Database.txt")));

			while ((line = bf.readLine()) != null) {
				listWord.add(line);
			}
			bf.close();
		} catch (Exception e) {
		}
	}

	/**
	 * Ghi noi dung vao file voi duong dan path cua file do va noi dung text
	 * 
	 * @param path
	 * @param text
	 */
	public void writeFile(String path, String text) {
		try {
			BufferedWriter bf = new BufferedWriter(new FileWriter(
					new File(path)));
			bf.write(text);
			bf.close();
		} catch (Exception e) {
		}
	}

	/**
	 * Tra ve word list trong file database.txt
	 * 
	 * @return
	 */
	public ArrayList<String> getListWord() {
		readFileDatabase();
		return this.listWord;
	}
}
